<?php

namespace app\api\model\house;

use app\api\model\house\HouseParkMedia;
use think\Db;
use think\Model;


class HousePark extends Model
{





    // 表名
    protected $name = 'house_park';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text',
        'house_type_text',
    ];

    public function getTypeTextAttr($value, $data)
    {
        //$value = $value ?: ($data['type'] ?? '');
        //$list = $this->getTypeList();
        //return $list[$value] ?? '';
        if (isset($data['type'])){
            $type = explode(',',$data['type']);
            $arr = [];
            foreach ($type as $k=>$v){
                array_push($arr,$this->getTypeList()[$v]);
            }
            return count($arr) > 0 ?implode(',',$arr) :  '';
        } else {
            return '';
        }

    }

    public function getTypeList()
    {
        return [1=>'公寓',2=>'楼房',3=>'别墅',4=>'其他'];
    }

    public function getHouseTypeTextAttr($value, $data)
    {
        //$value = $value ?: ($data['house_type'] ?? '');
        //$list = $this->getHouseTypeList();
        //return $list[$value] ?? '';
        if (isset($data['house_type'])){
            $house_type = explode(',',$data['house_type']);
            $arr = [];
            foreach ($house_type as $k=>$v){
                array_push($arr,$this->getHouseTypeList()[$v]);
            }
            return count($arr) > 0 ?implode(',',$arr) :  '';
        } else {
            return '';
        }

    }

    public function getHouseTypeList()
    {
        return [1=>'一室',2=>'二室',3=>'三室',4=>'多室'];
    }


    //添加园区
    public function add($user_id,$house_id,$params)
    {
        if (isset($params['media_json'])){
            $media_json = json_decode($params['media_json'],true)?json_decode($params['media_json'],true):_json_decode($params['media_json']);

        } else {
            $media_json = [];
        }

        $park_id = isset($params['park_id']) ? $params['park_id'] : 0;
        //$can_change = isset($params['can_change']) ? $params['can_change'] : 1;

        Db::startTrans();
        try {
            $park_model = new HousePark();

            $park_data = [
                'name'=>$params['name'],
                'brand'=>$params['brand'],
                'address'=>$params['address'],
                'lat'=>$params['lat'],
                'lng'=>$params['lng'],
                'property_company_name'=>$params['property_company_name'],
                'property_company_mobile'=>$params['property_company_mobile'],
                'contact_name'=>$params['contact_name'],
                'contact_mobile'=>$params['contact_mobile'],
                'area'=>$params['area'],
                'floor_num'=>$params['floor_num'],
                'room_num'=>$params['room_num'],
                'parking_spot_num'=>$params['parking_spot_num'],
                'type'=>$params['type'],
                'house_type'=>$params['house_type'],
                'complement_id'=>$params['complement_id'],
                'scenic_id'=>$params['scenic_id'],
                'manage_id'=>$params['manage_id'],
            ];
            if ($park_id){

                $info = HousePark::get($park_id);
                if ($info['can_change']==1){
                    HouseParkMedia::where(['park_id'=>$park_id])->delete();
                    $res = $park_model->validate('HousePark.add')->save($park_data,['park_id'=>$park_id]);
                    if ($res === false) {
                        return [
                            'code'=>0,
                            'data'=>'',
                            'msg'=>$park_model->getError()
                        ];
                    }
                }

            } else {
                $park_data['user_id'] = $user_id;
                //$park_data['house_id'] = $house_id;
                $res = $park_model->validate('HousePark.add')->save($park_data);
                if ($res === false) {
                    return [
                        'code'=>0,
                        'data'=>'',
                        'msg'=>$park_model->getError()
                    ];
                }
                $park_id = $park_model->park_id;

                House::where(['house_id'=>$house_id])->update(['park_id'=>$park_id]);
            }

            $media_model = new HouseParkMedia();
            $media_list = [];
            foreach ($media_json as $k=>$v){
                $media_list[] = [
                    'park_id'=>$park_id,
                    'category_id'=>$v['category_id'],
                    'media'=>$v['media'],
                    'title'=>$v['title'],
                ];
            }
            $media_model->saveAll($media_list);


            Db::commit();
            return [
                'code'=>1,
                //'data'=>$res
            ];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return [
                'code'=>0,
                'data'=>'',
                'msg'=>$e->getMessage()
            ];
            //throw new \Exception($e->getMessage());
        }


    }


    //编辑园区
    public function edit($park_id,$params)
    {
        $info = HousePark::get($park_id);
        $media_json = json_decode($params['media_json'],true)?json_decode($params['media_json'],true):_json_decode($params['media_json']);

        Db::startTrans();
        try {
            $park_model = new HousePark();

            $park_data = [
                'name'=>$params['name'],
                'brand'=>$params['brand'],
                'address'=>$params['address'],
                'lat'=>$params['lat'],
                'lng'=>$params['lng'],
                'property_company_name'=>$params['property_company_name'],
                'property_company_mobile'=>$params['property_company_mobile'],
                'contact_name'=>$params['contact_name'],
                'contact_mobile'=>$params['contact_mobile'],
                'area'=>$params['area'],
                'floor_num'=>$params['floor_num'],
                'room_num'=>$params['room_num'],
                'parking_spot_num'=>$params['parking_spot_num'],
                'type'=>$params['type'],
                'house_type'=>$params['house_type'],
                'complement_id'=>$params['complement_id'],
                'scenic_id'=>$params['scenic_id'],
                'manage_id'=>$params['manage_id'],
            ];

            if ($info['can_change']==1){
                $res = $park_model->validate('HousePark.edit')->save($park_data,['park_id'=>$info['park_id']]);
                if ($res === false) {
                    return [
                        'code'=>0,
                        'data'=>'',
                        'msg'=>$park_model->getError()
                    ];
                }

                HouseParkMedia::where(['park_id'=>$info['park_id']])->delete();
                $media_model = new HouseParkMedia();
                $media_list = [];
                foreach ($media_json as $k=>$v){
                    $media_list[] = [
                        'park_id'=>$info['park_id'],
                        'category_id'=>$v['category_id'],
                        'media'=>$v['media'],
                        'title'=>$v['title'],
                    ];
                }
                $media_model->saveAll($media_list);
            }

            Db::commit();
            return [
                'code'=>1,
                //'data'=>$res
            ];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return [
                'code'=>0,
                'data'=>'',
                'msg'=>$e->getMessage()
            ];
            //throw new \Exception($e->getMessage());
        }
    }

    //详情
    public function getInfo($park_id)
    {

        $park_info = HousePark::get($park_id);

        //照片分类
        $media_list = [];
        $media_category = HouseMediaCategory::where(['type'=>1])->order('weigh desc')->field('id,name')->select();

        foreach ($media_category as $k=>$v){
            $list = HouseParkMedia::where(['park_id'=>$park_id,'category_id'=>$v['id']])->select();

            if (count($list)){
                $media_list[] = [
                    'title'=>$v['name'],
                    'data'=>$list
                ];
            }
        }
        $park_info['media_list'] = $media_list;
        //物业管理
        $manage_category_list = HouseManageCategory::order('weigh desc')->field('id,name')->select();
        foreach ($manage_category_list as $k=>$v){
            $manage_category_list[$k]['child'] = HouseManage::where('id','in',$park_info['manage_id'])
                ->order('weigh desc')->field('name')->select();
        }
        $park_info['manage_list'] =  $manage_category_list;

        //园区配套
        $house_park_complement_model = new HouseParkComplement();
        $type_list = $house_park_complement_model->getTypeList();
        $park_complement_list = [];
        foreach ($type_list as $k=>$v){
            $list = HouseParkComplement::where(['type'=>$k])
                ->where('id','in',$park_info['complement_id'])
                ->order('weigh desc')->field('name')->select();
            if (count($list)>0){
                $park_complement_list[] = [
                    'title'=>$v,
                    'data'=>$list
                ];
            }
        }
        $park_info['park_complement_list'] = $park_complement_list;
        return $park_info;
    }

    //推荐
    public function recommend($params)
    {
        $num = isset($params['num']) ? $params['num'] : 10;
        $city_id = isset($params['city_id']) ? $params['city_id'] : 0;//城市

        //$house_id = House::where(['city_id'=>$city_id,'status'=>1])->column('house_id');

        $where = ['status'=>1,'is_recommend'=>1];

        /*if (count($house_id)==0){
            return  [];
        } else {
            $where['house_id'] = ['in',$house_id];
        }*/

        $field = 'park_id,name,brand,address,floor_num,room_num,parking_spot_num,type,house_type';

        $list = HousePark::where($where)
            ->field($field)
            ->order('is_top desc is_recommend desc')
            //->order('createtime desc')
            ->limit($num)->select();

        foreach ($list as $k=>$v){
            $media = HouseParkMedia::where(['park_id'=>$v['park_id']])
                ->order('createtime asc')->column('media');
            $list[$k]['cover'] = count($media)>0?$media[0]:'';
        }

        return $list;
    }

    //园区列表
    public function lists($params)
    {
        $page_size = isset($params['page_size']) ? $params['page_size'] : 10;

        $keyword = isset($params['keyword']) ? $params['keyword'] : '';//关键词搜索
        $city_id = isset($params['city_id']) ? $params['city_id'] : 0;//城市

        //$house_id = House::where(['city_id'=>$city_id,'status'=>1])->column('house_id');
        //$house_id = House::where(['status'=>1])->column('house_id');

        $where = ['status'=>1];

        /*if (count($house_id)==0){
            return  [];
        } else {
            $where['house_id'] = ['in',$house_id];
        }*/

        if(!empty($keyword)){
            $where['name'] = ['like',"%$keyword%"];
        }

        $field = 'park_id,name,brand,address,floor_num,room_num,parking_spot_num,type,house_type,can_change';

        $list = HousePark::where($where)
            ->field($field)
            ->order('createtime desc')
            ->paginate($page_size, false, ['query' => request()->get()]);

        foreach ($list as $k=>$v){
            $media = HouseParkMedia::where(['park_id'=>$v['park_id']])
                ->order('createtime asc')->column('media');
            $list[$k]['cover'] =  count($media)>0?$media[0]:'';
        }

        return $list;
    }
}
